package cn.pconline.autoclub.web.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.Photo;
import cn.pconline.autoclub.entity.PhotoPraise;
import cn.pconline.autoclub.entity.PhotoReply;
import cn.pconline.autoclub.entity.PhotoUserPraise;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.AlbumService;
import cn.pconline.autoclub.service.CensorPhotoReplyService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.DynaService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.PhotoPraiseService;
import cn.pconline.autoclub.service.PhotoReplyService;
import cn.pconline.autoclub.service.UserService;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.StringUtil;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.app.AppControllerStatic;
import cn.pconline.autoclub.web.UserAuth;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouruxuan
 * @date 2015年2月28日 下午2:51:05
 * 
 * 相册评论，相册点赞相关接口
 */
@Controller
@RequestMapping(value = "/appapi")
public class AppPhotoController {

	@Autowired
	private AlbumService albumService;
	
	@Autowired
	private ClubService clubService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private UserAuth userAuth;
	
	@Autowired
	private DynaService dynaService;
	
	@Autowired
	private PhotoReplyService photoReplyService;
	
	@Autowired
    private PhotoPraiseService photoPraiseService;
	
	@Autowired
    private MessageService messageService;
	
    @Autowired
    private CensorPhotoReplyService censorPhotoReplyService;
    
    @Autowired
    private SystemConfig systemConfig;
	
	private static final Logger log = LoggerFactory.getLogger(AppPhotoController.class);
	
	/**
	 * 评论照片
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/1.0/photo/replyPhoto.do", method = RequestMethod.POST)
	public void replyPhoto(HttpServletRequest request, HttpServletResponse response) {
		//获取相关参数
        WebUtils.setEncoding4App(request, response);
        
        long albumId = AppControllerStatic.paramAlbumId(request);
        long photoId = AppControllerStatic.paramPhotoId(request);
        String content = AppControllerStatic.paramContent(request);
        long postToPhotoReplyId = WebUtils.paramLong(request, "postToPhotoReplyId", 0);
        
        JSONObject jsonObject = new JSONObject();
        
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "用户没登录", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //判断照片是否存在
        Photo photo = albumService.getValidPhoto(photoId, albumId);
        if(photo == null) {
        	AppControllerStatic.printErrorMsg(response, "评论的照片不存在", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //被回复的评论是否存在
        PhotoReply pr = null;
        if(postToPhotoReplyId > 0) {
        	pr = photoReplyService.findPhotoReplyById(postToPhotoReplyId, photoId);
            if(pr == null) {
            	AppControllerStatic.printErrorMsg(response, "被回复的评论不存在", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
                return;
            }
            //不可以回复自己的照片评论
            if(pr.getCreateBy() == user.getUid()) {
            	AppControllerStatic.printErrorMsg(response, "不可以回复自己发表的照片评论", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
                return;
            }
        }
        
        if(StringUtils.isEmpty(content)) {
        	AppControllerStatic.printErrorMsg(response, "评论内容不可以为空", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        if(StringUtils.length(content) > 150) {
        	AppControllerStatic.printErrorMsg(response, "评论内容长度不可以超过150", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //设置照片评论对象
        PhotoReply photoReply = new PhotoReply();
        photoReply.setAlbumId(albumId);
        photoReply.setContent(content);
        photoReply.setCreateAt(new Date());
        photoReply.setCreateBy(user.getUid());
        photoReply.setPhotoId(photoId);
        photoReply.setPostToPhontoReplyId(postToPhotoReplyId);
        //如果直接回复照片，被回复人为照片发布者
        if(postToPhotoReplyId == 0) {
        	photoReply.setPostToUserId(photo.getCreateBy());
        } else {//评论照片者
        	photoReply.setPostToUserId(pr.getCreateBy());
        }
       
        photoReply.setStatus(PhotoReply.STATUS_NORMAL);
        
        //增加照片评论
        long id = photoReplyService.createPhotoReply(photoReply);
        if(id <= 0) {
        	AppControllerStatic.printErrorMsg(response, "评论失败", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        //照片评论数+1
        photoReplyService.updatePhotoClunt(photoId, albumId, 1);
        
        //发送到审核平台
        censorPhotoReplyService.notifyCensorSystemCreate( request, photoReply );
        
        //收到的回复发送
        photoReplyService.setJson4BipToListReply( photoReply, photo );
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 获取评论总数,赞数
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/1.0/photo/getReplyPraiseCount.do", method = RequestMethod.GET)
	public void getReplyPraiseCount(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding4App(request, response);
        
        long albumId = AppControllerStatic.paramAlbumId(request);
        long photoId = AppControllerStatic.paramPhotoId(request);
        
        JSONObject jsonObject = new JSONObject();
        
        //判断照片是否存在
        Photo photo = albumService.getValidPhoto(photoId, albumId);
        if(photo == null) {
        	AppControllerStatic.printErrorMsg(response, "照片不存在", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        Album album = albumService.getValidAlbum(albumId);
        if(album == null) {
        	AppControllerStatic.printErrorMsg(response, "相册不存在", jsonObject , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        long count = photo.getPostCount();
        jsonObject.put("replyCount", count);
        jsonObject.put("praiseCount", photo.getPraiseCount());
        jsonObject.put("albumId", albumId);
        jsonObject.put("photoId", photoId);
        jsonObject.put("clubId", album.getClubId());
        jsonObject.put("photoCreateBy", photo.getCreateBy());
        jsonObject.put("albumCreateBy", album.getCreateBy());
        
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
	}
	
	/**
	 * 根据照片ID，获取照片评论列表
	 * @param request
	 * @param response
	 */
	@ResponseBody
    @RequestMapping(value = "/1.0/photo/getReplyList.do", method = RequestMethod.GET)
	public void getReplyList(HttpServletRequest request, HttpServletResponse response){
		WebUtils.setEncoding4App(request, response);
		
        long photoId = AppControllerStatic.paramPhotoId(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        
        Pager<PhotoReply> pager = photoReplyService.pagerPhotoReplyByPhotoId(photoId, 1, pageNo, pageSize);
        if(pager != null && !pager.getResultList().isEmpty()){
        	for(PhotoReply photoReply : pager.getResultList()){
        		JSONObject json = new JSONObject();
        		
        		json.put("photoId", photoReply.getPhotoId());
        		json.put("albumId", photoReply.getAlbumId());
        		json.put("photoReplyId", photoReply.getPhotoReplyId());
        		json.put("content", xssEncode == 0 ? photoReply.getContent() : EncodeUtils.encodeForHTMLFilterNull(photoReply.getContent()));
        		json.put("createDate", photoReply.getCreateAt());
        		json.put("userId", photoReply.getCreateBy());
        		json.put("postToDynaReplyId", photoReply.getPostToPhontoReplyId());
        		json.put("postToUserId", photoReply.getPostToUserId());
        		
        		User user = userService.findUser(photoReply.getCreateBy());
        		json.put("nickname", user == null ? "" : user.getNickname());
        		
        		User user2 = userService.findUser(photoReply.getPostToUserId());
        		json.put("postToNickName", user2 == null ? "" : user2.getNickname());
        		
        		jsonArray.add(json);
        	}
        }
        
        jsonObject.put("replyList", jsonArray);
        
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, null, pager, AppControllerStatic.V1_VERSION_LATEST);
        
	}
	
    /**
     * 1.2.17 获取照片点赞用户列表
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/photo/getPraiseUserList.do")
    public void getPraiseUserList(HttpServletRequest request, HttpServletResponse response){
         //获取相关参数
        WebUtils.setEncoding4App(request, response);
        long photoId = AppControllerStatic.paramPhotoId(request);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        if(photoId <= 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数photoId", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Pager<User> pager = photoPraiseService.getPraiseUserList(photoId, pageNo, pageSize);
        JSONObject jsonObject = new JSONObject();
        JSONArray users = new JSONArray();
        if(pager.getResultList() != null && !pager.getResultList().isEmpty()) {
            for(User user : pager.getResultList()) {
                JSONObject userJson = new JSONObject();
                userJson.put("userId", user.getUid());
                userJson.put("nickName", user.getNickname());
                users.add(userJson);
            }
        }
        jsonObject.put("userList", users);
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, null, pager, AppControllerStatic.V1_VERSION_LATEST);
    }
    
     /**
     * 用户收到的赞列表
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/photo/getPraiseList.do", method = RequestMethod.GET)
    public void getPraiseList(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding4App(request, response);
        int pageNo = AppControllerStatic.paramPageNo(request);
        int pageSize = AppControllerStatic.paramPageSize(request);
        JSONObject jsonObject = new JSONObject();
        //获取用户登录信息
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            AppControllerStatic.printErrorMsg(response, "用户末登录", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        Pager<PhotoUserPraise> pager = photoPraiseService.getPraiseList(user.getUid(), pageNo, pageSize);
        JSONArray arr = new JSONArray();
        if (pager != null && !pager.getResultList().isEmpty()) {
            for (PhotoUserPraise pup : pager.getResultList()) {
                User u = userService.findUser(pup.getUserId());
                if(u == null) {
                	continue;
                }
                JSONObject obj = new JSONObject();
                obj.put("userId", u.getUid());
                obj.put("nickName", u.getNickname());
                obj.put("isVip", u.getVip());
                obj.put("praiseTime", pup.getPraiseTime());
                obj.put("hadRead", pup.getIsRead());
                obj.put("createDate", DateUtils.format(pup.getPraiseTime(),"yyyy-MM-dd"));
                long photoId = pup.getPhotoId();
                long albumId = pup.getAlbumId();
                
                Album album = albumService.getValidAlbum( albumId );
                Photo photo = albumService.getPhotoById(photoId, albumId);
                if(photo != null && album!=null) {
                	obj.put("urlSmall", photo.getUrl144x144());
                	obj.put("urlBig", photo.getUrl700x());
                	obj.put("photoName", photo.getName());
                	
                	long clubId = album.getClubId();
                	Club club = clubService.getValidClub( clubId );
                	if(club!=null){
                		obj.put("dynaUrl", systemConfig.getRoot()+"/"+club.getClubUrl()+"/album/a"+albumId+"-"+photoId+"-show/");
                	}
                } else {
                	obj.put("urlSmall", "");
                	obj.put("urlBig", "");
                	obj.put("photoName", "");
                }
                obj.put("photoId", photoId);
                obj.put("albumId", albumId);
                arr.add(obj);
            }
        }
        jsonObject.put("praiseList", arr);
        AppControllerStatic.printSuccessMsgPager(response, jsonObject, null, pager, AppControllerStatic.V1_VERSION_LATEST);
    }
    
     /**
     * 未读点赞清零
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/photo/clearUnreadPraise.do", method = RequestMethod.POST)
    public void clearUnreadPraise(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding4App(request, response);
        String[] dynainfoIds = WebUtils.param(request, "photoIds", "").split(",");
        JSONObject jsonObject = new JSONObject();
        //获取用户登录信息
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            AppControllerStatic.printErrorMsg(response, "用户末登录", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        List<Long> ids = new ArrayList<Long>(dynainfoIds.length);
        for (String id : dynainfoIds) {
            try {
                ids.add(Long.parseLong(id));
            } catch (java.lang.NumberFormatException e) {
                continue;
            }
        }
        //已赞清零
        List<Long> rs = photoPraiseService.clearUnreadPraise(user.getUid(), ids);
        //去掉重复的动态ID
        HashSet<Long> set = new HashSet<Long>(rs);
        rs.clear();
        rs.addAll(set);
        
        jsonObject.put("successIds", StringUtil.toString(rs.toArray()));
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 1.2.18 判断是否已赞过照片
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/photo/getHadPraiseList.do")
    public void getHadPraiseList(HttpServletRequest request, HttpServletResponse response){
        //获取相关参数
        WebUtils.setEncoding4App(request, response);
        String photoIds = WebUtils.param(request, "photoIds", "");
        if(StringUtils.isEmpty(photoIds)) {
            AppControllerStatic.printErrorMsg(response, "非法参数photoIds", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        List<Long> photoIdList = new ArrayList<Long>();
        try {
        	for(String id : photoIds.split(",")) {
                photoIdList.add(Long.valueOf(id));
            }
        } catch(NumberFormatException exception) {
        	AppControllerStatic.printErrorMsg(response, "非法数字photoIds", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "用户没登录", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        List<PhotoPraise> praises = photoPraiseService.getPraiseList(user.getUid(), photoIdList);
        StringBuilder hadPraisePhotoIds = new StringBuilder();
        for(PhotoPraise photoPraise : praises) {
            hadPraisePhotoIds.append(',').append(photoPraise.getPhotoId());
        }
        JSONObject jsonObject = new JSONObject();
        if(StringUtils.isNotEmpty(hadPraisePhotoIds.toString())) {
        	jsonObject.put("hadPraisePhotoIds", hadPraisePhotoIds.substring(1));
        }else {
        	jsonObject.put("hadPraisePhotoIds", "");
        }
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
    }

    /**
     * 1.2.19 未读照片已赞数
     * @param request
     * @param response
     */
    @RequestMapping(value = "/1.0/photo/getUnReadCount.do")
    public void getUnReadCount(HttpServletRequest request, HttpServletResponse response){
        //获取相关参数
        WebUtils.setEncoding4App(request, response);
        User user = userAuth.getUser(request, response);
        if(user == null || user.getUid() == User.ANONYMOUS.getUid()) {
            AppControllerStatic.printErrorMsg(response, "用户没登录", null , null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        JSONObject jsonObject = new JSONObject();
        PhotoUserPraise photoPraise = photoPraiseService.getLatestPraise(user.getUid());
        int unReadCnt = photoPraiseService.getUnReadCount(user.getUid());
        if(photoPraise != null) {
            User praiseBy = userService.findUser(photoPraise.getUserId());
            jsonObject.put("praiseNotReadCount", unReadCnt);
            if(praiseBy != null) {
                jsonObject.put("latestPraiseMsg", praiseBy.getNickname());
            } else {
                jsonObject.put("latestPraiseMsg", "");
            }
            
            jsonObject.put("latestPraiseTime", photoPraise.getPraiseTime().getTime());
        } else {
            jsonObject.put("praiseNotReadCount", 0);
            jsonObject.put("latestPraiseMsg", "");
            jsonObject.put("latestPraiseTime", "");
        }
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
    }
    
    /**
     * 点赞/取消赞
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/photo/doPraise.do", method = RequestMethod.POST)
    public void doPraise(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding4App(request, response);
        JSONArray praisePhotoIds = WebUtils.parseArray(request, "praisePhotoIds");
        JSONArray unPraisePhotoIds = WebUtils.parseArray(request, "unPraisePhotoIds");
        JSONObject jsonObject = new JSONObject();
        //获取用户登录信息
        User user = userAuth.getUser(request, response);
        if (user == null || user.getUid() == 0) {
            AppControllerStatic.printErrorMsg(response, "用户未登录", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //点赞、取消赞两个数组不可以同时为空
        if (praisePhotoIds == null && unPraisePhotoIds == null) {
            AppControllerStatic.printErrorMsg(response, "参数有误", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        //点赞操作
        JSONArray failPraiseIds = new JSONArray();
        if (praisePhotoIds != null) {
            for (int i = 0; i < praisePhotoIds.size(); i++) {
                JSONObject obj = null;
                //判断是否转换成功
                try {
                	obj = praisePhotoIds.getJSONObject(i);
                	if (!photoPraiseService.doPraise(user.getUid(), obj.getLongValue("photoId"), obj.getLongValue("albumId"), PhotoPraise.STATUS_PRAISE)) {
                        failPraiseIds.add(obj);
                    }	
                } catch(Exception exception) {
                	log.error("[praisePhotoIds] fail to get photo, data={}", obj);
                	AppControllerStatic.printErrorMsg(response, "参数有误", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
                    return;
                }
            }
        }
        //取消赞操作
        JSONArray failNotPraiseIds = new JSONArray();
        if (unPraisePhotoIds != null) {
            for (int i = 0; i < unPraisePhotoIds.size(); i++) {
                JSONObject obj = null;
                //判断是否转换成功
                try {
                	obj = unPraisePhotoIds.getJSONObject(i);
                	if (!photoPraiseService.doPraise(user.getUid(), obj.getLongValue("photoId"), obj.getLongValue("albumId"), PhotoPraise.STATUS_UNPRAISE)) {
                        failNotPraiseIds.add(obj);
                	}
                }catch (Exception e) {
                	log.error("[unPraisePhotoIds] fail to get photo, data={}", obj);
                	e.printStackTrace();
                	AppControllerStatic.printErrorMsg(response, "参数有误", jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
                    return;
                }
            }
        }
        
        //返回操作结果
        jsonObject.put("createAt", System.currentTimeMillis());
        if (failPraiseIds.isEmpty() && failNotPraiseIds.isEmpty()) {
            AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
        } else {
        	jsonObject.put("failPraisePhotoIds", failPraiseIds);
            jsonObject.put("failUnPraisePhotoIds", failNotPraiseIds);
            AppControllerStatic.printErrorMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
        }
    }
    
    /**
     * 照片尺寸
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/photo/getPhotoUpcComm.do", method = RequestMethod.GET)
    public void getPhotoUpcComm(HttpServletRequest request, HttpServletResponse response) {
    	WebUtils.setEncoding4App(request, response);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commands", AppControllerStatic.UPC_COMMAND_PHOTO);
        AppControllerStatic.printSuccessMsg(response, jsonObject, null, AppControllerStatic.V1_VERSION_LATEST);
        
    }
    
}
